const fs = require('fs');
const path = require('path');

var command = process.argv[2];
var name = process.argv[3];
var filePath = path.join(__dirname, 'sysFile')
var files = fs.readdirSync(filePath);
var list = [];
var times = [];

function time(ctimeMs){
    var date1 = new Date(ctimeMs);
    var year = date1.getFullYear();
    var month = date1.getMonth()+1;
    var day = date1.getDate();
    var hour = date1.getHours();
    var minute = date1.getMinutes();
    return year+'-'+month+'-'+day+' '+hour+':'+minute;
}
function delDir(fpath){
    if(fs.existsSync(fpath)){
        if(fs.statSync(fpath).isFile()){
            fs.unlinkSync(fpath);
        }else{
            var f = fs.readdirSync(fpath);
            for(var i=0; i<f.length; i++){
                var cpath = path.join(fpath, '/'+f[i]);
                var file = fs.statSync(cpath);
                if(file.isFile()){
                    fs.unlinkSync(cpath);
                }else if(file.isDirectory()){
                    delDir(cpath);
                }
            }
            fs.rmdirSync(fpath);
        }
    }else{
        console.log("文件路径不存在");
    }
}

for(var i=0; i<files.length; i++){
    var childPath = path.join(filePath, "/"+files[i]);
    var file = fs.statSync(childPath);
    if(i == 0){
        times.push(file);
    }else{
        if(file.ctimeMs<=times[0].ctimeMs){
            times.unshift(file);
        }else{
            times.push(file);
        }
    }
}
for(var i=0; i<times.length; i++){
    var fileObj = {};
    fileObj.fileName = files[i];
    fileObj.fileSize = times[i].size;
    fileObj.createTime = time(times[i].ctimeMs);
    list.push(fileObj);
}
if(command == '-list'){
    console.log(list);
}else if(command == '-show'){
    if(files.indexOf(name)<0){
        console.log("该文件不存在！");
        process.exit();
    }else{
        console.log((fs.readFileSync(path.join(filePath,"/"+name))).toString());
        process.exit();
    }
}else if(command == '-del'){
    var fpath = path.join(filePath, "/"+name);
    delDir(fpath);
}